var _newname = "img_default.jpg";
var current_file = "";
var currentImage = "";

$(function(){
    var _txtpresentation_val = "";
    var _mode = "";
    var _membre = "";
	
    var _filename = "";
	
    var _x 		= 130;
    var _y 		= 175;
    var _imgW 	= 0;
    var _imgH 	= 0;

    /* JQUERY_EXTEND */
    $.extend({ 		
		
        // MEBRES
        initMembre : function(){
            //editorTXT('#txtpresentacion');
			
            $("#jqGrid").jqGrid({
                // <MODIFICAR>
                url: './Queries/query-membresAdmin.php?id='+1+'nd='+new Date().getTime(),
                colNames:['int_id_membres_admin', ' ', 'Noms & Pr&eacute;noms', 'Statuts', 'Depuis', 'Dates', 'Etat'],
                colModel:[
                {
                    hidden:true, 
                    search:false, 
                    name:'int_id_membres_admin', 
                    index:'int_id_membres_admin', 
                    align:'left'
                },

                {
                    name:'txt_photo_html', 
                    sortable: false, 
                    index:'txt_photo_html', 
                    width:35, 
                    align:'center'
                },

                {
                    name:'var_noms', 
                    sortable: false, 
                    index:'var_noms', 
                    align:'left'
                },

                {
                    name:'var_status', 
                    sortable: false, 
                    index:'var_status', 
                    align:'left'
                },

                {
                    name:'var_dates', 
                    sortable: false, 
                    index:'var_dates', 
                    align:'left'
                },

                {
                    search:false, 
                    hidden:true, 
                    sortable: false, 
                    name:'int_mem_order', 
                    index:'int_mem_order', 
                    align:'center'
                },

                {
                    search:false, 
                    sortable: false, 
                    name:'var_htmldesc', 
                    index:'var_htmldesc', 
                    align:'left'
                }
                ],
                sortname: ['int_id_membres_admin'],
                sortorder: "asc",
                width: 746,
                height: 300,
                // </MODIFICAR>
				
                loadtext: 'Chargement..',
                datatype: "json",
                pager: $('#jqpager'),
                rowNum:10,
                rowList:[10,20,50],	
                viewrecords: true,
                multiselect: true
            });
            
        }, 
        insertMembre : function(_var_photo, _var_noms, _var_status, _var_dates, _int_mem_order,_int_id_sections_view, _int_id_state){
			
            $.post("./?ws=MembreAdmin&act=insertMembre", {
                _var_photo: _var_photo, 
                _var_noms:_var_noms, 
                _var_status:_var_status, 
                _var_dates:_var_dates, 
                _int_mem_order:_int_mem_order,
                _int_id_sections_view:_int_id_sections_view, 
                _int_id_state:_int_id_state, 
                cache:Math.random()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert($.trim(data));
                    $.modal.close();
                }
            });
        },
        updateMembre : function(_id, _var_photo, _var_noms, _var_status, _var_dates,_int_id_sections_view, _int_id_state){
            $.post("./?ws=MembreAdmin&act=updateMembre", {
                _id:_id, 
                _var_photo: _var_photo, 
                _var_noms:_var_noms, 
                _var_status:_var_status, 
                _var_dates:_var_dates, 
                _int_id_sections_view:_int_id_sections_view, 
                _int_id_state:_int_id_state, 
                cache:Math.random()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert( $.trim(data) );
                    $.modal.close();
                }
                else $.modal.close();
            });
        },
        getMembre: function(_id){

            $.post("./?ws=MembreAdmin&act=getMembre", {
                _id:_id, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    var _data = Array();
                    _data = data.split('_%_');
					
                    $('#txtnom').val( $.trim(_data[0]) ); 
                    $('#txtstatus').val( $.trim(_data[1]) );
                    $('#txtdates').val( $.trim(_data[2]) );
                    selectCbo( '#cboetat', $.trim( _data[3]) );
                    _newname = _data[4];
                    currentImage = _newname;
                    $.getFilePath( _newname );
                    iconError(false,"Document ajout&eacute;.");	
                    validateForm();
                }
            });
        },
        deleteMembre: function(_ids){
            $.post("./?ws=MembreAdmin&act=deleteMembre", {
                _ids:_ids, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert(data);
                }
            });
        },
        uploadFile : function(_folder, _sizeLimit, _multi, photos){
            var current_file = "";
			
            $("#fileUpload").fileUpload({   
                uploader: './Resouces/js/uploader/uploader.swf',   
                cancelImg: './Resouces/js/uploader/cancel.png',   
                folder: _folder,   
                buttonText: 'Parcourir',
                checkScript: './Resouces/js/uploader/check.php',  
                width:110,
                height:35,
                fileDesc: "Format de l'image *.jpg uniquement",
                fileExt: '*.jpg',
				
                sizeLimit: _sizeLimit,
                script: './Resouces/js/uploader/upload.php',   
                multi: _multi,   
                simUploadLimit: 1, 
				
                onProgress: function(event,queueID,fileObj,data){
                    current_file = queueID;
                    $("#btn-save").attr("disabled","-1");
                },
                onSelect: function(event,queueID,fileObj){
                    _newname =  fileObj.name;
                    $('#lbl-okfile').html('');
                    $('#lbllien').html('');
                    window.frames[0].document.location="./Views/iframe/membres_index.html";
                },
                onSelectOnce: function(event,data){
                    $('#fileUpload').fileUploadStart();
                },
                onCancel: function(event,queueID,fileObj,data){
                    $("#btn-save").removeAttr("disabled");
                },
                onError: function(event,queueID,fileObj,errorObj){
                    $("#btn-save").removeAttr("disabled");
                //iconError(false,"Image ajout&eacute;.");
                },
                onComplete: function(event,queueID,fileObj,response,data){
                    $("#btn-save").removeAttr("disabled");					
                    _newname = fileObj.name;
                    iconError(false,"Image ajout&eacute;.");
                    //$.getFilePath( _newname );
                    $.getImageXY( _newname );
                }
            });   
			
        },
        getFilePath : function(_path){
            $.post("./?ws=MembreAdmin&act=getFilePath", {
                _path:_path, 
                cache:new Date().getTime()
                }, function(data){
                if($.trim(data)!=""){
                    $('#lbllien').html($.trim(data));	
                }
            });
        },
        getImageXY: function(_path){
            $.post("./?ws=MembreAdmin&act=getImagenXY", {
                _path:_path, 
                cache:new Date().getTime()
                }, function(data){
                if($.trim(data)!=""){
                    var _data = Array();
					
                    _data = data.split('_%_');
			 	
                    _imgW = $.trim(_data[0]);
                    _imgH = $.trim(_data[1]);
                    _newname = $.trim(_data[2]);
					

                    $( window.frames[0].document ).find('#cropbox').attr('width',_imgW);
                    $( window.frames[0].document ).find("#cropbox").attr("height", _imgH);
                    $( window.frames[0].document ).find("#cropbox").attr("src","../../../images/membres/"+_newname);
					
                    $( window.frames[0].document ).find('#preview').css({
                        width:_x, 
                        height: _y
                    });
                    $( window.frames[0].document ).find("#preview").attr("src","../../../images/membres/"+_newname);
                    $( window.frames[0].document ).find('#preview-layer').css({
                        width:_x, 
                        height: _y
                    });
                    $( window.frames[0].document ).find("#preview").attr("width", _x);
                    $( window.frames[0].document ).find("#preview").attr("height", _y);

                    window.frames[0].iniciar(_imgW, _imgH);
                    $("#file-uploader").css( {
                        display: "none"
                    } );
                    $("#cut-image").fadeIn();
                }
                else alert($.trim(data));
            });
			
        }
		
    // END MEBRES

    });
    /* END JQUERY_EXTEND */
	
    function validateForm(){
        $('#txtnom').select();
        _form = $("#frm-membre").validate({
            event: "blur",
            rules:{ 
                'txtnom': "required",
                'txtstatus': "required",
                'txtdates': "required",
                'cboetat': "required"	
            },
            messages:{
                'txtnom': "Entrer le nom & prénom du membre.",
                'txtstatus': "Entrer le statut.",
                'txtdates': "Entrer la date.",
                'cboetat': "S&eacute;lectionnez l'&eacute;tat"
            }
        });	
		
        function disabledControls(val){
            if(val){
                $('#txtnom').attr('disabled','-1'); 
                $('#txtstatus').attr('disabled','-1');
                $('#txtdates').attr('disabled','-1');
                $('#cboetat').attr('disabled','-1');;
            }
            else{
                $('#txtnom').removeAttr('disabled'); 
                $('#txtstatus').removeAttr('disabled');
                $('#txtdates').removeAttr('disabled');
                $('#cboetat').removeAttr('disabled');

                $("#btn-save").removeAttr('disabled');
            }
        }

        // SAVE FORM
        $("#frm-membre").submit(function(){
            if(_form.valid()){
                disabledControls(true);
                if(_mode == "update"){
                    if(_newname !=""){
                        disabledControls(false);
                        $.updateMembre(_membre, _newname, $('#txtnom').val(), $('#txtstatus').val(), $('#txtdates').val(), 1, $('#cboetat').val() );
                    } 
                    else{ 
                        iconError(true, "S&eacute;lectionnez une image!");
                        disabledControls(false);
                    }
                }
                else{
                    if(_newname ==""){
                        iconError(true, "S&eacute;lectionnez une image!");
                        disabledControls(false);
                    }
                    else{
                        //disabledControls(false);
                        $.insertMembre(_newname, $('#txtnom').val(), $('#txtstatus').val(), $('#txtdates').val(), 9999, 1, $('#cboetat').val() );
                    }
                }	
            }
			
            return false;
        });
    };
	
    function selectCbo(_idcbo, _intval){
        $(_idcbo+" option").each(function (){
            if($(this).val() == _intval){
                $(this).attr('selected','selected'); 
            }
        });
    }
	
    $("#btn-cancel").click( function(){
        if(currentImage != _newname) deleteMemebreImage( _newname );
        $.modal.close();
    });

    $("#sinsert").click( function(){
        _mode = "insert";
        _filename = ""
		
        _newname = "img_default.jpg";

        $('#Nouveau-title').html("Ajouter un membre");
        $("#Nouveau").modal({
            position: [0,0],
            opacity: 25,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                        $.uploadFile( '/csme.fr/images/membres', '15091456', false, false );
                        validateForm();
                    });
                });
            }			
        });
    });
	
    $("#supdate").click(function(){
        var s = $("#jqGrid").getGridParam('selarrrow');
        _filename = ""
        _mode = "update";
        _newname = "";
        $('#Nouveau-title').html("Modifier le membre");
        switch(s.length)
        {
            case 0:
                alert('Avertissement!\nS\u00E9lectionnez un membre parmi la liste.');
                break;
			
            case 1:
                _membre = s[0];
                $.getMembre( _membre );
                $("#Nouveau").modal({
                    position: [0,0],
                    opacity: 45,
                    autoResize: true,
                    onOpen: function (dialog){
                        dialog.overlay.fadeIn('fast', function (){
                            dialog.container.fadeIn('fast', function (){
                                dialog.data.show();
                                $.uploadFile( '/csme.fr/images/membres', '15091456', false, false );
                                validateForm();
                            });
                        });
                    }			
                });
                break;
			
            default:
                alert('Avertissement\nS\u00E9lectionnez seulement un membre \u00E0 la fois.');
                ;
                break;
        }
    });

    $("#sdelete").click(function(){
        if(_intUserT == 1){
            _mode = 'delete';
			
            var gr = $("#jqGrid").getGridParam('selrow');
	
            if( gr != null ) 
            {
                var s = $("#jqGrid").getGridParam('selarrrow');
                var f = s.toString();
                var j =  f.split(',');

                if(confirm("Eliminer membre(s)\nVous avez selection\u00E9 "+j.length+" membre(s).\nVoulez vous vraiment l'effacer(s)?")){
                    $.deleteMembre(f);
                }
            }
            else{
                alert('Avertissement\nS\u00E9lectionnez les membres \u00E0 effacer.');
            }
        }
    });


    //Initializing
    $.initMembre();


});

function iconError(_bool, _title){
    $('#lbl-okfile').css('display','none');
    var _icon = "";
    if(_bool) _icon = './Resouces/images/cancelfield.png';
    else _icon = './Resouces/images/okfield.png';
	
    $('#lbl-okfile').html('<img src="'+_icon+'" alt="'+_title+'" title="'+_title+'" />');
    $('#lbl-okfile').fadeIn();
}

function deleteMemebreImage(_pathname){
    $.post("./?ws=MembreAdmin&act=deleteMembreImage", {
        _path:_pathname, 
        cache:new Date().getTime()
    }, function(data){
        if($.trim(data)!=""){																																																						
        }
    });
}

function makeJcrop(){	
    $("#file-uploader").css( {
        display: "block"
    } );
    deleteMemebreImage( _newname );
    iconError(true, "S&eacute;lectionnez une image!");
    _newname = "";
    _filename = "";
    $("#cut-image").fadeOut();
}
function selectedImage(x,y,w,h){
    $("#file-uploader").css( {
        display: "block"
    } );
    $.getFilePath( _newname );
    $.post("./?ws=MembreAdmin&act=CutImage", {
        x:x,
        y:y,
        w:w,
        h:h,
        _path:_newname, 
        cache:new Date().getTime()
        }, function(data){ 																														
        if($.trim(data)!=""){
            _newname = $.trim(data);
            $("#cut-image").fadeOut();
        }
        else alert($.trim(data));
    });
}